package ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class TestReentrantLock2 {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try{
                //如果没有竞争那么此方法就会获取Lock对象锁
                //如果有竞争就进入阻塞队列，可以被其他线程用interrupt方法打断
                log.debug("尝试获得锁");
                //lock.lockInterruptibly();可以被打断，打断后不会再去获取锁
                lock.lockInterruptibly();
                //lock.lock()会一直尝试获取锁
                //lock.lock();
            }catch(InterruptedException e){
                e.printStackTrace();
                log.debug("没有获得锁，返回");
                return;
            }

            try{
                log.debug("获取到锁");
            }finally {
                lock.unlock();
            }
        },"t1");
        lock.lock();
        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.debug("打断t1");
        //打断t1后，t1不会继续获得锁
        t1.interrupt();
    }
}
